//
//  JSSStatusViewModel.swift
//  WeiBoItem
//
//  Created by jss on 16/4/21.
//  Copyright © 2016年 jss. All rights reserved.
//

import UIKit
import SDWebImage
import YYText
import SVProgressHUD

class JSSStatusViewModel: NSObject {
    
    //定义个JSSStatusModel属性 以便中间做属性连接
    var statusModel:JSSStatusModel? {
        
        didSet {
            
            //原创微博会员图标的处理
            dealVipImage()
            //转发微博内容前面拼接@符号和转发的原作者的处理
            dealRetweetText()
            //原创微博来源的截取处理
            dealSourceContent()
            
            //把下面方法执行计算出的图片大小返回给转发微博配图的size
            retweetStatusViewPictureSize = calculatePictureSize(statusModel?.retweeted_status?.pic_urls)
            
            //把下面方法执行计算出的图片大小返回给原创微博配图的size
            originalStatusViewPictureSize = calculatePictureSize(statusModel?.pic_urls)
            
            //print("配图大小\(retweetStatusViewPictureSize)")
            
            //处理格式化时间
            //            dealCreateTimer()
            //先把创建时间格式化好
            createDate = self.formateCreateAsNSdate(statusModel?.created_at)
            
           originalAttrString = self.attrbutedText(statusModel?.text ?? "")
            
        }
    }
    
    
    //原创微博用户的会员图标
    var vipImage:UIImage?
    
    //转发微博的内容
    var retweetText:String?
    
    //原创微博来源
    var sourceContent:String?
    //"<a href="http://weibo.com" rel="nofollow">新浪微博</a>"
    
    //转发微博配图大小
    var retweetStatusViewPictureSize:CGSize = CGSizeZero
    
    //原创微博的配图大小
    var originalStatusViewPictureSize:CGSize = CGSizeZero
    
    //距离当前时间的微博创建时间
    var createTimeText: String? {
        
        return dealCreateTimer(createDate ?? NSDate())
    }
    
    
    //原创微博的副文本内容
    var originalAttrString:NSAttributedString?
    //转发微博的副文本内容
    var retweetAttrString:NSAttributedString?
    
    //记录格式化好的当前时间
    private var createDate:NSDate?
    
    
    //处理首页微博图片表情和特殊字符的高亮
    func attrbutedText(text:String)->NSAttributedString {
        
        
        //原生的副文本
        let attributeString = NSMutableAttributedString(string: text)
        
        var res = [JSSMatchResult]()
        //匹配出表情字符串  \\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]
        
        (text as NSString).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u2E80-\\u9FFF]+\\]") { (count, captureString, captureRange, _) -> Void in
            print("\(captureString.memory)------\(captureRange.memory)")
            
            let result = JSSMatchResult(captureString: captureString.memory!, range: captureRange.memory)
            
            print("result=================\(result)")
            res.append(result)
        }
        
        //为了防止越界崩溃  这里倒着遍历
        for value in res.reverse(){
        
            //通过表情字符串找到相应的表情模型
            if let emoticon = JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.emoticonWithChs(value.captureString as String){
                
                //print(emoticon)
                //通过表情模型生成的表情图片副文本
                let image = UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: JSSEmoticonkeyboardViewModel.EmoticonkeyboardSharedViewModel.emoticonBundle, compatibleWithTraitCollection: nil)
                
               //-----------以下代码是yytext实现 设置副文本因为yytext里面不支持Attachment  它自己有相对应的方法实现-------
                //文字附件大小
                let font = UIFont.systemFontOfSize(JSSStatusContentFont)
              
                let attr = NSMutableAttributedString.yy_attachmentStringWithContent(image, contentMode: UIViewContentMode.ScaleAspectFill, attachmentSize: CGSize(width: font.lineHeight, height: font.lineHeight), alignToFont: font, alignment: YYTextVerticalAlignment.Center)
                
                
                
                
                //--------一下代码实现的效果也可以用yytext来实现------
                
//                //初始化文字附件
//                let atta = JSSTextAttachmentModel()
//                atta.image = image
//                //设置文字附件大小
//                
//                let font = UIFont.systemFontOfSize(JSSStatusContentFont)
//                atta.bounds = CGRect(x: 0, y: -5, width:font.lineHeight , height: font.lineHeight)
//                //初始化一个副文本
//                let attr = NSAttributedString(attachment: atta)
              // 把对应的位置的表情文字替换
                attributeString.replaceCharactersInRange(value.range, withAttributedString: attr)

            }
        
        }
        
        //添加特殊文字颜色
        //话题
        linkColor("#[^#]+#", attributeSting: attributeString)
        //带@符号的
        linkColor("@[\\u4e00-\\u9fa5A-Za-z0-9_\\-]+", attributeSting: attributeString)
        //url
        linkColor("([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.',;]*)?", attributeSting: attributeString)
        
        return attributeString
    
    }
    
    func linkColor(regex:String,attributeSting:NSMutableAttributedString){
    
       (attributeSting.string as NSString).enumerateStringsMatchedByRegex(regex) { (_, captureString, captureRange, _) -> Void in
        
         print("\(captureString.memory)-------\(captureRange.memory)")
        
        let color = UIColor(red: 80/255, green: 125/255, blue: 175/255, alpha: 1)
        
        
        //特殊字段的字体颜色
        attributeSting.addAttribute(NSForegroundColorAttributeName, value: color, range: captureRange.memory)
        
        //设置高亮
//        YYTextBorder *border = [YYTextBorder borderWithFillColor:[UIColor grayColor] cornerRadius:3];
//        
//        YYTextHighlight *highlight = [YYTextHighlight new];
//        [highlight setColor:[UIColor whiteColor]];
//        [highlight setBackgroundBorder:highlightBorder];
//        highlight.tapAction = ^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect) {
//            NSLog(@"tap text range:...");
//            // you can also set the action handler to YYLabel or YYTextView.
//        };
//        
//        // 2. Add 'highlight' attribute to a range of text.
//        [attributedText yy_setTextHighlight:highlight range:highlightRange];
        
        
        //初始化一个背景对象
        let border = YYTextBorder(fillColor: UIColor(red: 177/255, green: 215/255, blue: 255/255, alpha: 1), cornerRadius: 3)
        //初始化一高亮对象
        let hiligted = YYTextHighlight()
        //设置颜色
        hiligted.setColor(color)
        //设置高亮的背景
        hiligted.setBackgroundBorder(border)
        
        //把captureString.memory是NSString类型转换成string类型
        let re = (captureString.memory!) as String
        
        hiligted.tapAction = {(containerView:UIView,text:NSAttributedString,range:NSRange,rect:CGRect)->() in
        
            print("高亮字符点击了")
            
            SVProgressHUD.showInfoWithStatus(re)
        }
        
        //将高亮对象添加到attributeString里面
        attributeSting.yy_setTextHighlight(hiligted, range: captureRange.memory)
            

        }
  
    }
    
    
    //通过把一个"创建时间"的字符串格式化成 Nsdate
    private func formateCreateAsNSdate(createAt:String?)->NSDate? {
        
        //取到时间字符串
        guard let create_at = createAt else {
            return nil
        }
        
        //把时间字符串转化成 NSDate
        let format = NSDateFormatter()
        format.locale = NSLocale(localeIdentifier: "en")
        // 2015-08-10 10:10:10 yyyy-MM-dd HH:mm:ss
        
        //Sun Nov 22 11:25:56 +0800 2015
        format.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        //把微博创建时间 时间格式化
        let createDate = format.dateFromString(create_at)!
        //print(createDate)
        
        //返回格式化好的时间
        return createDate
        
        
    }
    
    
    //处理时间的方法
    func dealCreateTimer(createDate: NSDate)->String {
        
        //拿到时间字符串
        //        guard let create_at = statusModel?.created_at else{
        //            return
        //        }
        
        //转成NSDate
        //初始化时间格式化
        let formarte = NSDateFormatter()
        //指定格式字符串
        
        formarte.locale = NSLocale(localeIdentifier: "en")
   
        let canlendar = NSCalendar.currentCalendar()
        
        
        //与当前时间进行对比
        if isThisYear(createDate){//createDate是否是今年
            // createTimeText = "是今年"
            //如果是今天
            if canlendar.isDateInToday(createDate){//是今天
                //获得当前时间
                let currentDate = NSDate()
                //求 创建时间 到现在的时间差
                let timeInterval = currentDate.timeIntervalSinceDate(createDate)
                
                if timeInterval < 60 {//一分钟之前
                    return "1分钟前"
                    
                }else if timeInterval < 60 * 60 {//是否是一小时之内
                    return "\(Int(timeInterval) / 60)分钟前"
                }else {//多少小时前
                    return "\(Int(timeInterval) / 3600)/小时前"
                }
                
            }else if canlendar.isDateInYesterday(createDate) {//是昨天
                formarte.dateFormat = "昨天 HH:mm"
                return formarte.stringFromDate(createDate)
                
                
            }else { //其他天
                formarte.dateFormat = "MM-dd HH:mm"
                return formarte.stringFromDate(createDate)
                
            }
            
        }else{
            //createTimeText = "不是今年"
            formarte.dateFormat = "yyyy-MM-dd HH:mm"
            return formarte.stringFromDate(createDate)
        }

    }
    
    //传入一个时间 与当前时间进行对比 返回是否是当前时间的年份
    func isThisYear(targetTime:NSDate)->Bool{
        
        //取到当前时间
        let currentTime = NSDate()
        
        let formate = NSDateFormatter()
        formate.dateFormat = "yyyy"
        
        //取出两个时间的年份
        let targetYear = formate.stringFromDate(targetTime)
        let currentYear = formate.stringFromDate(currentTime)
        
        //            if targetYear == currentYear{
        //
        //                return true
        //
        //            }else{
        //
        //                return false
        //            }
        
        return targetYear == currentYear
        
    }
    
    
    
    
    
    
    
    
    //更新单张图片配图大小
    func updateSiglePictureSize() {
        
        retweetStatusViewPictureSize = calculateSinglePictureSize(statusModel?.retweeted_status?.pic_urls)
        originalStatusViewPictureSize = calculateSinglePictureSize(statusModel?.pic_urls)
    }
    
    
    //计算单张微博的配图大小(让一张图片的内容按原比例显示)
    private func calculateSinglePictureSize(pic_urls:[JSSPictureInfoModel]?)->CGSize {
        //取出图片地址
        guard let url = pic_urls?.first?.thumbnail_pic else {
            
            return CGSizeZero
        }
        
        //取出图片的地址 取到已经下载好的图片--->从缓存中取
        if let picture = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(url) {
            
            //SDWebImage会根据当前屏幕的缩放比对图片进行缩放
            //如果想让图片正常显示的话 就要把缩放比调整回来
            //获取屏幕的缩放比
            let scale = UIScreen.mainScreen().scale
            
            var size = CGSize(width: picture.size.width * scale, height: picture.size.height * scale)
            
            //如果图片宽度小于50 把图片的宽度拉伸到50 高度等比例缩放
            if size.width < 50 {
                
                let height = 50 / size.width * size.height
                size.width = 50
                size.height = height > 100 ? 100 : height
            }
            return size
            
        }
        
        return CGSizeZero
    }
    
    
    
    //通过配图数据 计算图片大小   返回计算结果
    private func calculatePictureSize(pic_urls:[JSSPictureInfoModel]?)->CGSize {
        
        //pic_urls 配图数组
        
        //获取图片的张数
        let count = pic_urls?.count ?? 0
        //如果配图数量是0张返回CGSizeZero
        if count == 0 {
            
            return CGSizeZero
        }
        
        //根据图片的张数(count) 计算出大小
        //第一步:.求出几列几行(微博最多显示3列3行)
        //另外一种简便方法
        // let column = (count == 4) ? 2 : count > 3 ? 3 : count
        var column = count > 3 ? 3 : count
        //算法   count = 5 --> (5-1)/3 + 1
        let row = (count - 1) / 3 + 1
        
        //如果是四张图片 那么显示 2  列(配图的特殊点 一张 四张 图片)
        if count == 4 {
            column = 2
        }
        //第二步: 求出每一张图片的大小 并且设置每张图片之间的间距大小
        //设置间距
        let margin:CGFloat = 5
        
        //求出每一张图片的宽高(设置宽高相等)
        let picW = (SCREENW - 2 * JSSStatusMargin - 2 * margin) / 3
        let picH = picW
        
        //根据每一张图片的大小和列数求出宽度 行数求出高度
        //根据每一张配图的宽高算出 配图数组的总宽度
        let width = CGFloat(column) * picW + CGFloat(column - 1) * margin
        //根据每一张配图的宽高算出 计算出配图的总高度
        let height = CGFloat(row) * picH + CGFloat(row - 1) * margin
        
        //返回宽高
        return CGSize(width: width, height: height)
        
    }
    
    
    //处理微博来源字符串
    func dealSourceContent() {
        
        //"<a href="http://weibo.com" rel="nofollow">新浪微博</a>"
        if let content = statusModel?.source {
            
            //开始截取字符串
            if let startIndex = content.rangeOfString("\">")?.endIndex,let endIndex = content.rangeOfString("</")?.startIndex {
                
                let rel = content.substringWithRange(startIndex..<endIndex)
                
                sourceContent = "来自\(rel)"
            }
        }
    }
    
    //处理转发微博的内容
    func dealRetweetText() {
        
        if let text = statusModel?.retweeted_status {
            
            if let name = text.user?.name,let contentText = text.text {
                
                retweetText = "@\(name)\(contentText)"
                
                retweetAttrString = self.attrbutedText(retweetText!)
                
            }
        }
    }
    
    //原创微博会员图标的处理
    func dealVipImage() {
        
        if let rank = statusModel?.user?.mbrank where rank > 0 && rank < 7 {
            
            vipImage = UIImage(named: "common_icon_membership_level\(rank)")
        }
    }
}
